/**
 *
 */
import RightContent from '@/components/GlobalHeader/RightContent';
import { ConnectState } from '@/models/connect';
import { isLogin, storageClear } from '@/utils/utils';
import ProLayout, {
  BasicLayoutProps as ProLayoutProps,
  MenuDataItem,
  Settings,
} from '@ant-design/pro-layout';
import { connect } from 'dva';
import React, { useEffect, useState } from 'react';
import { Dispatch } from 'redux';
import Link from 'umi/link';
import router from 'umi/router';
import logo from '../assets/logo.svg';
import PageLoading from '../components/PageLoading';
import AuthSimpleLayout from './AuthSimpleLayout';
import './BasicLayout.less';
import { Helmet } from 'react-helmet';
export let umiDispatch = null
export let editGlobalState = null

export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
}
const BasicLayout: React.FC<BasicLayoutProps> = props => {
  const { dispatch, children, settings, location = { pathname: '/' }, editGlobal } = props;

  umiDispatch = dispatch;
  editGlobalState = editGlobal;

  /**
   * constructor
   */
  const [menuData, setMenuData] = useState([]);
  const [logoUrl, setLogoUrl] = useState('');
  const [thumbnailLogoUrl, setThumbnailLogoUrl] = useState('');
  const [isFold, seFold] = useState(false);
  useEffect(() => {
    if (isLogin()) {
      dispatch({
        type: 'menu/getMenuData',
        callback: response => {
          setMenuData(response.menuData);
          setLogoUrl(response.logoUrl ? `//images.weserv.nl/?url=${response.logoUrl}` : '');
          setThumbnailLogoUrl(response.thumbnailLogoUrl ? `//images.weserv.nl/?url=${response.thumbnailLogoUrl}` : '');
        },
      });
      //引入
      const scriptInfo = document.createElement("script")
      scriptInfo.setAttribute("data-callType","callScript")
      scriptInfo.src = "https://oseats.dfiov.com.cn:443/im/104eac.html"
      document.body.appendChild(scriptInfo)
    } else {
      storageClear();
      router.replace('/user/login');

      //删除
      let callScript = document.querySelector("script[data-callType='callScript']")
      if(callScript){
      document.body.removeChild(callScript)
      window.location.reload();
      }
    }
  }, []);
  const [transition, setTransition] = useState("");

  const transit = (direction: string) => {
     setTransition("transition-" + direction);
     setTimeout(() => {
     setTransition("");
     }, 500);
   };
  /**
   * init variables
   */
  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
    //菜单未折叠false，显示主logo，菜单折叠true显示缩略logo
    if (payload) {
      seFold(true);
      transit("left");
    } else {
      seFold(false);
      transit("right");
    }
  };

  const treeToArray = (tree: any[]) => {
    let res: any[] = []
    for (const item of tree) {
      const { children, rounts, ...i } = item
      if (children && children.length) {
        res = res.concat(treeToArray(children))
      }
      res.push(i)
    }
    return res
  }

  const getPageInfo = (pathname: string, tree: any) => {
    const tempList = treeToArray(tree)
    let res: any = {}
    tempList.some((item: any) => {
      const state = item.resourceLevelCode === pathname;
      if (state) {
        res = item;
      }
      return state;
    })
    return res;
  }

  const buryingPoint = (data: any) => {
    dispatch({
      type: 'http/postObjWithRes',
      payload: {
        url: '/menu/buryingPoint/save',
        ...data,
      },
      callback: (res: any) => {}
    })
  }

  let newRoute: any = [];
  return isLogin() ? (
    <ProLayout
      logo={isFold ? (thumbnailLogoUrl ? thumbnailLogoUrl : false) : (logoUrl ? logoUrl : false)}
      menuHeaderRender={(logoDom, titleDom) => (
        <div style={isFold? {maxWidth: '53px', marginLeft: '5px'} : {maxWidth: '212px'}} className={transition}>
        <Link to="/">
          {logoDom}
        </Link>
        </div>
      )} 
      onCollapse={handleMenuCollapse} // 菜单的折叠收起事件
      onPageChange={(e: any) => {
        const pageLevelCode = e?.pathname.slice(1).split('/')[0];
        menuData.some((item: any) => {
          const tempLevelCode = item.resourceLevelCode?.slice(1).split('/')[0];
          const status = pageLevelCode ===  tempLevelCode;
          if (status) {
            const pageInfo = getPageInfo(e?.pathname, [item])
            if (pageInfo.resourceIcon === 'menu') {
              const postMenuData = {
                currentMenuCode: pageInfo.resourceLevelCode,
                currentMenuName: pageInfo.resourceName,
                rootMenuCode: item.resourceLevelCode,
                rootMenuName: item.resourceName
              }
              buryingPoint(postMenuData)
            }
          }
          return status
        })
      }}
      siderWidth={224} //侧边栏宽度，默认256
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl || menuItemProps.children) {
          return defaultDom;
        }
        return <Link to={menuItemProps.path}>{defaultDom}</Link>;
      }} // 自定义菜单项的 render 方法
      breadcrumbRender={(routers = []) => {
        newRoute = [{ path: '/', breadcrumbName: '首页' }].concat(routers);
        return [
          {
            path: '/',
            breadcrumbName: '首页',
          },
          ...routers,
        ];
      }} // 自定义面包屑的数据
      itemRender={(route, params, routes, paths) => {
        // 路径里面包含就可以跳转
        const first = routes.indexOf(route) === 0;
        return first ? (
          <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        ) : (
          <span>{route.breadcrumbName}</span>
        );
      }}
      footerRender={false}
      menuDataRender={() => menuData} // 菜单的数据
      rightContentRender={() => <RightContent menuData={newRoute} />}
      {...props}
      {...settings}
    >
      <Helmet>
        <title>{'东风车联网管理平台'}</title>
        <meta name="description" content={'东风车联网管理平台'} />·{' '}
      </Helmet>
      <AuthSimpleLayout location={location}>{children}</AuthSimpleLayout>
    </ProLayout>
  ) : (
    <PageLoading />
  );
};

export default connect(({ global, settings, loading, editGlobal  }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
  editGlobal
}))(BasicLayout);
